from threading import Thread
import traceback
import Queue

class Task:

    def __init__(self,callback,*args,**kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def do(self):
        if self.callback :
            self.callback(*self.args,**self.kwargs)

class Worker(Thread):

    def __init__(self,i,queue):
        Thread.__init__(self,name=i)
        self.queue = queue
        self.stoped = False

    def run(self):
        while not self.stoped:
            task = self.queue.get()
            try:
                print "--------------------in thread:",self.getName(),"-----------------------"
                task.do()
            except:
                traceback.print_stack()

    def stop(self):
        self.stoped = True

class ThreadPool:

    def __init__(self,size):
        self.workers = []
        self.queue = Queue.Queue()
        for i in range(size):
            work = Worker(i,self.queue)
            self.workers.append(work)
            work.setDaemon(True)
            work.start()

    def processTask(self,task):
        self.queue.put(task);

    def shutdown(self):
        for work in self.workers :
            work.stop()